package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        //  https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
        Map<String,String> map = new HashMap();
        map.put("client_id","1654186154");
        map.put("client_secret","8685e496d3d8b2c1a6148be67cb0e8a2");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);

        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(),null, map);


        if(response.getStatusLine().getStatusCode()==200){
            //获取access_toker
            String json = EntityUtils.toString(response.getEntity());
            SocialUser user = JSON.parseObject(json, SocialUser.class);
            //知道当前是哪个社交用户
            //1. 第一次登陆，要将这个社交用户注册进去

            R r = memberFeignService.oauthLogin(user);
            if(r.getCode()==0){

                String member = JSON.toJSONString(r.get("member"));
                MemberResVo res = JSON.parseObject(member, MemberResVo.class);

                session.setAttribute("loginUser",res);

                System.out.println("登录成功：" +res);
                return "redirect:http://gulimall.com";
            }else{
                return "redirect:http://auth.gulimal.com/login.html";
            }


        }else{
            return "redirect:http://auth.gulimal.com/login.html";
        }




    }

}
